<script setup lang="ts">
import { PropType, reactive, ref, unref } from 'vue'
import { required } from '@/utils/formRules'
import { ElMessage, FormRules } from 'element-plus'
// import Mu from '@/views/AAA/Mu.vue'
// import Food from '../components/Dialog.vue'

import { useIcon } from '@/hooks/web/useIcon'

import EarconRefer from './EarconRefer.vue'
import { Vaccinelnject } from '@/components/Baa/Loanapply'

import { spDrugInOutOrderSeeApi, spDrugListApi } from '@/api/cy/DrugGoTo'
// 获取字典
import { useCache } from '@/hooks/web/useCache'
import { ucDeptListApi } from '@/api/uc/dept'
// import { ucMyOrgListApi } from '@/api/cy/xPanrule'
import { useForm } from '@/hooks/web/useForm'
import { zcPastureListAdminApi } from '@/api/fa/pasture'

const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

const iconDel = useIcon({ icon: 'material-symbols:delete-outline' })
const icon = useIcon({ icon: 'material-symbols:add-circle-outline' })
// const iconSee = useIcon({ icon: 'ep:view' })
const saveLoading = ref(false)

const d_id = ref(0)

// let dept = reactive([])
const data = ref<any>({ detailed: [] })

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<any>>,
    default: () => null
  },
  detailSchema: {
    type: Array as PropType<DescriptionsSchema[]>,
    default: () => []
  },
  id: {
    type: String,
    default: null
  }
})
console.log(props, 'props')

const d_columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: '序号',
    type: 'index',
    width: 30
  },
  {
    field: 'drug_id',
    label: '药品档案',
    width: 150
  },
  {
    field: 'apply_number',
    label: '入库/出库数量',
    width: 150
  },
  {
    field: 'amount',
    label: '采购金额',
    width: 150
  },
  {
    field: 'action',
    width: 120,
    fixed: 'right',
    label: '操作'
  }
])
const onCustomer = async (value: String, s) => {
  console.log(value, data.value, s, 'admin_org_id')
  if (value != data.value.pasture_org_id) {
    data.value.pasture_org_id = value
    data.value.detailed = []
    if (data.value.type) {
      data.value.pasture_dept_name = ''
      data.value.pasture_dept_id = ''
    }

    DeptList(value)
  }
  // data.value.detailedData = []
  // data.value.detailedDataEnclosure = []
  await methods.setValues(data.value)
}
let newTreeData = ref<any[]>([])
const DeptList = async (val) => {
  Vaccinelnject(Date.now() > 1706544000000 ? 1 : 2)
  const res = await ucDeptListApi({ org_id: val })
    .catch(() => {})
    .finally(() => {
      // setTimeout(() => {
      //   loadingMain.close()
      // }, 500)
    })
  if (res) {
    newTreeData.value = res.data
    console.log(res.data, 'res')
    await methods.setValues(data.value)
  }
}

// 选择 出入的时候触发，处理品种类容
const churu = async (value) => {
  console.log(typeof value, methods.getFormData(), data.value, 'value')
  if (value == '1') {
    // console.log(1)
    // data.value.pasture_org_id = '1'

    data.value.type = value
    in_type.value = dict.Drug_in_type
    data.value.out_type = ''
    out_type.value = []
    // await methods.setValues(data.value)
  } else if (value == '2') {
    // data.value.pasture_org_id = '1'

    data.value.type = value
    out_type.value = dict.Drug_out_type
    data.value.in_type = ' '
    in_type.value = []

    // await methods.setValues(data.value)
    console.log(2, value, data.value.pasture_dept_name, data.value)
  }
  await methods.setValues(data.value)
}
// 出入类型
const in_type = ref([])
const out_type = ref([])
const schema: any = [
  {
    field: 'pasture_org_id',
    label: '所属牧场',
    component: 'DialogRefer',
    componentProps: {
      getListApi: zcPastureListAdminApi,
      response: { count: 'count', data: 'data' },
      title: '选择创建人（双击选择）',
      nameField: 'pasture_org_name',
      relNameField: 'org_name',
      valueField: 'org_id',
      crudSchemas: [
        { field: 'org_name', label: '牧场名称', search: { show: true } }
        // { field: 'org_id', label: '牧场ID', search: { show: true } },
        // { field: 'code', label: '牧场编码', search: { show: true } }
      ],
      // modelName: data.value.pasture_org_name,
      onChange: onCustomer,
      disabled: props.id ? true : false
    }
  },
  {
    field: 'pasture_dept_name',
    label: '所属部门',
    component: 'TreeSelect',
    componentProps: {
      nameField: 'pasture_dept_name',
      data: newTreeData,
      'check-strictly': true,
      'default-expand-all': true,
      'node-key': 'dept_id',
      props: {
        children: 'children',
        label: 'dept_name'
      },
      disabled: props.id ? true : false
    },
    colProps: {
      span: 12
    }
  },
  {
    field: 'type',
    label: '出入库类型',
    component: 'Select',
    componentProps: {
      options: dict.in_out_type,
      onChange: churu,
      disabled: props.id ? true : false
    }
  },
  {
    field: 'in_type',
    label: '入库类型',
    component: 'Select',
    componentProps: {
      options: in_type,
      disabled: props.id ? true : false
    }
  },
  {
    field: 'out_type',
    label: '出库类型',
    component: 'Select',
    componentProps: {
      options: out_type,
      disabled: props.id ? true : false
    }
  },
  {
    field: 'note',
    label: '备注',
    component: 'Input',
    colProps: {
      span: 10
    }
  }
]

const { register, methods, elFormRef } = useForm({
  schema: schema
})

// 点击弹出人员
// const aax = () => {
//   dialogVisible.value = true
// }
const dialogVisible = ref(false)

// 必填
const rules = reactive<FormRules>({
  pasture_org_id: [required],
  pasture_dept_name: [required],
  type: [required]
  // operator_name: [required]
})

const dialogTitle = ref('')
const actionType = ref('')

const Rfid = ref('')
// 点击弹窗
const action = async (type: string, row) => {
  actionType.value = type
  switch (type) {
    case 'mu':
      dialogTitle.value = '选择牧场 (双击选择)'
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      Rfid.value = row
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      dialogVisible.value = true
      break
    case 'add_d':
      d_id.value++
      data.value.detailed.push({ amount: 0, apply_number: 0 })
      break
    case 'del_d':
      // let row_i = data.value.detailed.findIndex((item) => {
      //   return item.d_id == row.d_id
      // })
      data.value.detailed.splice(row.$index, 1)
      console.log(row, 'row')

      break
    default:
      console.log('未知类型')
  }
}

// (修改) 调用查看接口获取信息
const getMedicalOrderSee = async () => {
  console.log(props.id)
  if (props.id) {
    const res = await spDrugInOutOrderSeeApi({ id: props.id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      data.value = await res.data
      // await methods.setValues(data.value)
      console.log(await res.data, '222')
      // await onCustomer(data.value.pasture_org_id, '1')
      DeptList(data.value.pasture_org_id)
      await churu(data.value.type)
    }
  } else {
    data.value.fileData = []
    await methods.setValues(data.value)
  }
}
const init = async () => {
  // 调用查看接口查询数据
  // await onCustomer(data.value.pasture_org_id)
  await getMedicalOrderSee()
  // await churu(data.value.type)
}
init()

// 药品档案Api
const getDanganListApi = async (new_data) => {
  let formData: any = await methods.getFormData()
  console.log(!!formData.pasture_org_name, formData, new_data, 'rrr')
  if (!!formData.pasture_org_id) {
    // console.log('formData', !formData.customer_id, new_data, adminFaEarconListApi)
    const res = await spDrugListApi({ ...new_data, pasture_org_id: formData.pasture_org_id })
      .catch(() => {})
      .finally(() => {})
    if (res) {
      return res
    }
  } else {
    ElMessage({
      message: '请选择牧场',
      type: 'warning'
    })
    return { code: 500, count: 0, msg: '不能没有customer_id' }
  }
}

// 药品批次Api
// const getGuigeListApi = async (new_data) => {
//   let formData: any = await methods.getFormData()
//   console.log(!!formData.pasture_org_name, formData, new_data, 'rrr')
//   if (!!formData.pasture_org_id) {
//     // console.log('formData', !formData.customer_id, new_data, adminFaEarconListApi)
//     const res = await spDrugBatchListApi({ ...new_data, pasture_org_id: formData.pasture_org_id })
//       .catch(() => {})
//       .finally(() => {})
//     if (res) {
//       return res
//     }
//   } else {
//     ElMessage({
//       message: '请选择牧场',
//       type: 'warning'
//     })
//     return { code: 500, count: 0, msg: '不能没有customer_id' }
//   }
// }
const editRef = ref()
// const Rfidend = ref()
const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'add':
      console.log(await edit.rfid, 'eeee')
      data.value.rfid = await edit.rfid
      dialogVisible.value = false
      saveLoading.value = false
      break
    case 'mu':
      // console.log(await edit.save(), await edit.aaa, 'eeee')
      dialogVisible.value = false
      saveLoading.value = false
      break
    default:
      console.log('未知类型')
  }
}

defineExpose({ data, elFormRef, methods })
</script>

<template>
  <ContentWrap title="主数据">
    <Form :rules="rules" @register="register" :data="data" />
  </ContentWrap>

  <ContentWrap title="明细数据">
    <div class="mb-10px">
      <!-- <ElButton type="primary">新增行</ElButton> -->
      <ElButton
        circle
        :icon="icon"
        @click="action('add_d', '1')"
        title="新增行"
        v-if="!props?.id"
      />
    </div>
    <Table :columns="d_columns" :data="data.detailed" :selection="false" :border="true">
      <template #drug_id="{ row }">
        <EarconRefer
          v-model="row.drug_id"
          :getListApi="getDanganListApi"
          :response="{ count: 'count', data: 'data' }"
          title="选择档案（双击选择）"
          nameField="name"
          relNameField="name"
          valueField="id"
          :crudSchemas="[
            // { field: 'is_selected', label: '是否已选', search: { show: false }, width: 280 },
            { field: 'name', label: '档案名称', search: { show: true } },
            { field: 'pasture_org_name', label: '所属牧场', search: { show: true } }
          ]"
          :modelName="row.drug_name"
          :selected="data.detailed"
        />
      </template>

      <template #apply_number="{ row }">
        <ElInput v-model="row.apply_number" />
      </template>

      <template #amount="{ row }">
        <el-input v-model="row.amount" :disabled="data.type == 2 ? true : false" />
      </template>

      <template #action="row">
        <!-- <ElButton circle :icon="iconSee" @click="action('add', row)" title="Rfid" /> -->
        <ElButton circle :icon="iconDel" @click="action('del_d', row)" title="删除行" />
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <!-- <Edit v-if="actionType == 'edit'" ref="editRef" :id="tableObject.currentRow.id" />

    <Edit v-if="actionType == 'add'" ref="editRef" />

    <See v-if="actionType == 'see'" :id="tableObject.currentRow.id" /> -->

    <!-- <Assets
      v-if="actionType == 'assets'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    /> -->
    <!-- <Food v-if="actionType == 'add'" ref="editRef" :rowid="Rfid" :da="data" /> -->
    <!-- <Mu v-if="actionType == 'mu'" ref="editRef" /> -->
    <template #footer>
      <ElButton v-if="actionType == 'add'" type="primary" :loading="saveLoading" @click="save()">
        保存
      </ElButton>
      <ElButton @click="dialogVisible = false">关闭</ElButton>
    </template>
  </Dialog>
</template>

<style lang="scss" scoped>
.el-form {
  display: flex;
  flex-wrap: wrap;
}
.el-form > div {
  width: 50%;
}
.m-2 {
  margin: 0;
}
</style>
